"""
Django settings for boxuser project.
自定义盲盒系统客户端设置
"""

import os
from pathlib import Path
import environ

# 初始化环境变量
env = environ.Env()

# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent

# 读取环境变量
environ.Env.read_env(os.path.join(BASE_DIR, '.env'))

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = env('SECRET_KEY', default='django-insecure-j7_9xmy@m^5i7rl-!nrjz$l^c&6j8^5j@#yj$g+)z=l&$j=qnk')

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = env('DEBUG', default=True)

# ALLOWED_HOSTS = ['localhost', '127.0.0.1', '0.0.0.0', '172.0.0.0']

# ljl add
SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https')

# 生产环境
ALLOWED_HOSTS = ['*']

# Application definition

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'django.contrib.sites',
    
    # 第三方应用
    'allauth',
    'allauth.account',
    'allauth.socialaccount',
    'crispy_forms',
    'crispy_bootstrap5',
    # 'debug_toolbar',
    
    # 自定义应用
    'accounts',
    'blindbox',
    'shopping',
    'order',
    'market',
    'analysis',
    'points',  # 积分应用
    'analytics',  # 用户行为跟踪应用
    'recommendation',  # 智能推荐系统
    'chatbot',  # 聊天机器人应用
    'help_center',  # 帮助中心应用
    'boxuser.templatetags',  # 注册自定义模板标签库
]

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'whitenoise.middleware.WhiteNoiseMiddleware',  # 静态文件处理
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'allauth.account.middleware.AccountMiddleware',  # Django-allauth中间件
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
    # 'debug_toolbar.middleware.DebugToolbarMiddleware',  # Debug工具栏
    'accounts.middleware.UserBehaviorMiddleware',  # 用户行为跟踪中间件
]

# 用户行为跟踪配置
BEHAVIOR_TRACKING = {
    'ENABLED': True, 
    'EXCLUDE_PATHS': ['/static/', '/media/', '/admin/'],
}

ROOT_URLCONF = 'boxuser.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [os.path.join(BASE_DIR, 'templates')],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
                'shopping.context_processors.cart_count',  # 购物车数量上下文处理器
            ],
        },
    },
]

WSGI_APPLICATION = 'boxuser.wsgi.application'

# Database
# https://docs.djangoproject.com/en/5.0/ref/settings/#databases

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': env('DB_NAME', default='csmh'),
        'USER': env('DB_USER', default='root'),
        'PASSWORD': env('DB_PASSWORD', default='root'),
        'HOST': env('DB_HOST', default='localhost'),
        'PORT': env('DB_PORT', default='3306'),
        'OPTIONS': {
            'charset': 'utf8mb4',
        },
    }
}

# 自定义用户模型
AUTH_USER_MODEL = 'accounts.User'

# Password validation
# https://docs.djangoproject.com/en/5.0/ref/settings/#auth-password-validators

AUTH_PASSWORD_VALIDATORS = [
    {
        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
        'OPTIONS': {
            'max_similarity': 0.7,
        }
    },
    {
        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
        'OPTIONS': {
            'min_length': 8,
        }
    },
    {
        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
    },
]

# Internationalization
# https://docs.djangoproject.com/en/5.0/topics/i18n/

LANGUAGE_CODE = 'zh-hans'
TIME_ZONE = 'Etc/GMT-8'  # 使用UTC+8时区
USE_I18N = True
USE_L10N = True
USE_TZ = True

# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/5.0/howto/static-files/

STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
STATICFILES_DIRS = [
    os.path.join(BASE_DIR, 'static'),
]
STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage'

# Media files
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')

# Default primary key field type
# https://docs.djangoproject.com/en/5.0/ref/settings/#default-auto-field

DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'

# Crispy Forms
CRISPY_ALLOWED_TEMPLATE_PACKS = "bootstrap5"
CRISPY_TEMPLATE_PACK = "bootstrap5"

# Django AllAuth配置
AUTHENTICATION_BACKENDS = [
    'django.contrib.auth.backends.ModelBackend',
    'allauth.account.auth_backends.AuthenticationBackend',
]

SITE_ID = 1
LOGIN_REDIRECT_URL = '/'
LOGOUT_REDIRECT_URL = '/'

# 新的AllAuth配置格式
ACCOUNT_LOGIN_METHODS = {'username'}  # 使用用户名登录
ACCOUNT_SIGNUP_FIELDS = ['username*', 'email', 'password1*', 'password2*']  # *表示必填字段
ACCOUNT_EMAIL_VERIFICATION = 'none'  # 可选: 'mandatory'

# 聊天机器人配置sk-34ca6bad403c43529b1f079613c7bb68
DEEPSEEK_API_KEY = env('DEEPSEEK_API_KEY', default='sk-34ca6bad403c43529b1f079613c7bb68')  # 使用环境变量或默认值

# 内部IP
INTERNAL_IPS = ['127.0.0.1']

# 日志配置
LOG_DIR = os.path.join(BASE_DIR, 'logs')
os.makedirs(LOG_DIR, exist_ok=True)  # 确保日志目录存在

LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    'formatters': {
        'verbose': {
            'format': '{levelname} {asctime} {module} {message}',
            'style': '{',
        },
    },
    'handlers': {
        'file': {
            'level': 'INFO',
            'class': 'logging.FileHandler',
            'filename': os.path.join(LOG_DIR, 'django.log'),
            'formatter': 'verbose',
        },
        'user_behavior': {
            'level': 'INFO',
            'class': 'logging.FileHandler',
            'filename': os.path.join(LOG_DIR, 'user_behavior.log'),
            'formatter': 'verbose',
        },
        'recommendation': {
            'level': 'INFO',
            'class': 'logging.FileHandler',
            'filename': os.path.join(LOG_DIR, 'recommendation.log'),
            'formatter': 'verbose',
        },
        'chatbot': {
            'level': 'INFO',
            'class': 'logging.FileHandler',
            'filename': os.path.join(LOG_DIR, 'chatbot.log'),
            'formatter': 'verbose',
        },
    },
    'loggers': {
        'django': {
            'handlers': ['file'],
            'level': 'INFO',
            'propagate': True,
        },
        'user_behavior': {
            'handlers': ['user_behavior'],
            'level': 'INFO',
            'propagate': False,
        },
        'recommendation': {
            'handlers': ['recommendation'],
            'level': 'INFO',
            'propagate': False,
        },
        'chatbot': {
            'handlers': ['chatbot'],
            'level': 'INFO',
            'propagate': False,
        },
    },
}

# 邮件配置
EMAIL_BACKEND = 'django.core.mail.backends.filebased.EmailBackend'
EMAIL_FILE_PATH = os.path.join(BASE_DIR, 'sent_emails')
DEFAULT_FROM_EMAIL = 'noreply@miaoqushiguang.com'

# DeepSeek API配置
DEEPSEEK_API_KEY = env('DEEPSEEK_API_KEY', default='')

# 如果要使用真实SMTP，可以取消注释下面的配置
# EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
# EMAIL_HOST = 'smtp.example.com'
# EMAIL_PORT = 587
# EMAIL_HOST_USER = 'your_email@example.com'
# EMAIL_HOST_PASSWORD = 'your_password'
# EMAIL_USE_TLS = True
# DEFAULT_FROM_EMAIL = 'your_email@example.com'

# 添加本地化配置
LOCALE_PATHS = [
    os.path.join(BASE_DIR, 'locale'),
]
